-
Notifications
You must be signed in to change notification settings - Fork 9
/
ChordPro.swift
487 lines (443 loc) · 18.2 KB
/
ChordPro.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//
// ChordPro.swift
// Chord Provider
//
// © 2024 Nick Berendsen
//
import SwiftUI
import SwiftlyChordUtilities
/// The `ChordPro` file parser
actor ChordPro {
// MARK: Parse a 'ChordPro' file
/// Parse a ChordPro file
/// - Parameters:
/// - text: The text of the file
/// - transpose: The optional transpose of the song
/// - id: The ID of the song
/// - instrument: The instrument of the song
/// - fileURL: The optional file url of the song
/// - Returns: A ``Song`` item
static func parse(id: UUID, text: String, transpose: Int, instrument: Instrument, fileURL: URL?) -> Song {
/// Start with a fresh song
var song = Song(id: id)
song.metaData.instrument = instrument
song.metaData.fileURL = fileURL
/// Add the optional transpose
song.metaData.transpose = transpose
/// And add the first section
var currentSection = Song.Section(id: song.sections.count + 1, autoCreated: true)
/// Parse each line of the text:
for text in text.components(separatedBy: .newlines) {
switch text.trimmingCharacters(in: .whitespaces).prefix(1) {
case "{":
/// Directive
processDirective(text: text, song: &song, currentSection: ¤tSection)
case "|":
/// Tab or Grid
if text.starts(with: "|-") || currentSection.type == .tab {
/// Tab
processTab(text: text, song: &song, currentSection: ¤tSection)
} else {
/// Grid
processGrid(text: text, song: &song, currentSection: ¤tSection)
}
case "":
/// Empty line
if !currentSection.lines.isEmpty && currentSection.autoCreated == false {
/// Start with a fresh line:
var line = Song.Section.Line(id: currentSection.lines.count + 1)
/// Add an empty part
/// - Note: Use a 'space' as text
let part = Song.Section.Line.Part(id: 1, chord: nil, text: " ")
line.parts.append(part)
currentSection.lines.append(line)
} else {
processSection(
label: Environment.none.rawValue,
type: .none,
song: &song,
currentSection: ¤tSection
)
}
case "#":
/// A remark; just ignore it
break
default:
switch currentSection.type {
case .tab:
/// A tab can start with '|--02-3-4|', but also with 'E|--2-3-4| for example
processTab(text: text, song: &song, currentSection: ¤tSection)
case .strum:
processStrum(text: text, song: &song, currentSection: ¤tSection)
default:
/// Anything else
processLine(text: text, song: &song, currentSection: ¤tSection)
}
}
}
/// Close the last section if needed
if !currentSection.lines.isEmpty {
song.sections.append(currentSection)
}
/// Set the first chord as key if not set manual
if song.metaData.key == nil {
song.metaData.key = song.chords.first
}
/// All done!
return song
}
// MARK: Process a directive
/// Process a directive
/// - Parameters:
/// - text: The text to process
/// - song: The `Song`
/// - currentSection: The current `section` of the `song`
private static func processDirective(
text: String,
song: inout Song,
currentSection: inout Song.Section
) {
if let match = text.firstMatch(of: directiveRegex) {
let directive = match.1
let label = match.2
switch directive {
case .none:
break
// MARK: Meta-data directives
case .t, .title:
song.definedMetaData.append(directive)
song.metaData.title = label ?? song.metaData.title
case .st, .subtitle, .artist:
song.definedMetaData.append(directive)
song.metaData.artist = label ?? song.metaData.artist
case .capo:
song.definedMetaData.append(directive)
song.metaData.capo = label
case .time:
song.metaData.time = label
case .key:
if let label, var chord = ChordDefinition(name: label, instrument: song.metaData.instrument) {
/// Transpose the key if needed
if song.metaData.transpose != 0 {
chord.transpose(transpose: song.metaData.transpose, scale: chord.root)
}
song.metaData.key = chord
}
case .tempo:
song.metaData.tempo = label
case .year:
song.definedMetaData.append(directive)
song.metaData.year = label
case .album:
song.definedMetaData.append(directive)
song.metaData.album = label
// MARK: Formatting directives
case .c, .comment:
if let label {
/// Start with a new line
var line = Song.Section.Line(id: currentSection.lines.count + 1)
line.comment = label
switch currentSection.type {
case .none:
/// A comment in its own section
processSection(
label: Environment.comment.rawValue,
type: Environment.comment,
song: &song,
currentSection: ¤tSection
)
currentSection.lines.append(line)
song.sections.append(currentSection)
currentSection = Song.Section(id: song.sections.count + 1, autoCreated: false)
default:
/// An inline comment, e.g. inside a verse or chorus
currentSection.lines.append(line)
}
}
// MARK: Environment directives
/// ## Start of Chorus
case .soc, .startOfChorus:
processSection(
label: label ?? Environment.chorus.rawValue,
type: .chorus,
song: &song,
currentSection: ¤tSection
)
/// ## Repeat Chorus
case .chorus:
processSection(
label: label ?? Environment.chorus.rawValue,
type: .repeatChorus,
song: &song,
currentSection: ¤tSection
)
song.sections.append(currentSection)
currentSection = Song.Section(id: song.sections.count + 1, autoCreated: false)
/// ## Start of Verse
case .sov, .startOfVerse:
processSection(
label: label ?? Environment.verse.rawValue,
type: .verse,
song: &song,
currentSection: ¤tSection
)
/// ## Start of Bridge
case .sob, .startOfBridge:
processSection(
label: label ?? Environment.bridge.rawValue,
type: .bridge,
song: &song,
currentSection: ¤tSection
)
/// ## Start of Tab
case .sot, .startOfTab:
processSection(
label: label ?? Environment.tab.rawValue,
type: .tab,
song: &song,
currentSection: ¤tSection
)
/// ## Start of Grid
case .sog, .startOfGrid:
processSection(
label: label ?? Environment.grid.rawValue,
type: .grid,
song: &song,
currentSection: ¤tSection
)
/// ## Start of Textblock
case .startOfTextblock:
processSection(
label: label ?? Environment.textblock.rawValue,
type: .textblock,
song: &song,
currentSection: ¤tSection
)
/// ## Start of Strum (custom)
case .sos, .startOfStrum:
processSection(
label: label ?? Environment.strum.rawValue,
type: .strum,
song: &song,
currentSection: ¤tSection
)
/// # End of environment
case .eoc, .endOfChorus, .eov, .endOfVerse, .eob, .endOfBridge, .eot, .endOfTab, .eog, .endOfGrid, .eos, .endOfTextblock, .endOfStrum:
processSection(
label: Environment.none.rawValue,
type: .none,
song: &song,
currentSection: ¤tSection
)
// MARK: Chord diagrams
case .define:
if let label {
processDefine(text: label, song: &song)
}
// MARK: Custom directives
case .musicPath:
if let label {
song.definedMetaData.append(directive)
song.metaData.musicPath = label
}
case .tag:
if let label {
song.metaData.tags.append(label.trimmingCharacters(in: .whitespacesAndNewlines))
}
case .instrument:
break
}
}
}
// MARK: Process a section
/// Process a section
/// - Parameters:
/// - label: The label of the `section`
/// - type: The type of `section`
/// - song: The `song`
/// - currentSection: The current `section` of the `song`
private static func processSection(label: String, type: Environment, song: inout Song, currentSection: inout Song.Section) {
if currentSection.lines.isEmpty {
/// There is already an empty section
currentSection.type = type
currentSection.label = label
currentSection.autoCreated = type == .none ? true : false
} else {
/// Make a new section
song.sections.append(currentSection)
currentSection = Song.Section(
id: song.sections.count + 1,
autoCreated: type == .none ? true : false
)
currentSection.type = type
currentSection.label = label
}
}
// MARK: Process a chord definition
/// Process a chord definition
/// - Parameters:
/// - text: The chord definition
/// - song: The `song`
private static func processDefine(text: String, song: inout Song) {
if var definedChord = try? ChordDefinition(definition: text, instrument: song.metaData.instrument, status: .unknownChord) {
definedChord.status = song.metaData.transpose == 0 ? definedChord.status : .customTransposedChord
/// Update a standard chord with the same name if there is one in the chords list
if let index = song.chords.firstIndex(where: {
$0.name == definedChord.name &&
($0.status == .standardChord || $0.status == .transposedChord)
}) {
/// Use the same ID as the standard chord
definedChord.id = song.chords[index].id
song.chords[index] = definedChord
} else {
/// Add the chord as a new definition
song.chords.append(definedChord)
}
}
}
// MARK: Process a tab environment
/// Process a tab environment
/// - Parameters:
/// - text: The text to process
/// - song: The `Song`
/// - currentSection: The current `section` of the `song`
private static func processTab(text: String, song: inout Song, currentSection: inout Song.Section) {
/// Start with a fresh line
var line = Song.Section.Line(id: currentSection.lines.count + 1)
line.tab = text.trimmingCharacters(in: .whitespacesAndNewlines)
currentSection.lines.append(line)
/// Mark the section as Tab if not set
if currentSection.type == .none {
currentSection.type = .tab
currentSection.label = Environment.tab.rawValue
}
}
// MARK: Process a grid environment
/// Process a grid environment
/// - Parameters:
/// - text: The text to process
/// - song: The `Song`
/// - currentSection: The current `section` of the `song`
private static func processGrid(text: String, song: inout Song, currentSection: inout Song.Section) {
/// Start with a fresh line:
var line = Song.Section.Line(id: currentSection.lines.count + 1)
/// Give the structs an ID
var partID: Int = 1
/// Seperate the grids
let grids = text.replacingOccurrences(of: " ", with: "").split(separator: "|")
for text in grids where !text.isEmpty {
var grid = Song.Section.Line.Grid(id: partID)
/// Process like a 'normal' line'
var matches = text.matches(of: lineRegex)
matches = matches.dropLast()
for match in matches {
let (_, chord, spacer) = match.output
if let chord {
let result = processChord(chord: String(chord), song: &song)
/// Add it as chord
grid.parts.append(Song.Section.Line.Part(id: partID, chord: result.id))
partID += 1
}
if let spacer {
/// Add it as spacer
for _ in spacer {
grid.parts.append(Song.Section.Line.Part(id: partID, chord: nil, text: "."))
partID += 1
}
}
}
line.grid.append(grid)
}
currentSection.lines.append(line)
/// Mark the section as Grid if not set
if currentSection.type == .none {
currentSection.type = .grid
currentSection.label = Environment.grid.rawValue
}
}
// MARK: Process a strum environment
/// Process a strum environment
/// - Parameters:
/// - text: The text to process
/// - song: The `Song`
/// - currentSection: The current `section` of the `song`
private static func processStrum(text: String, song: inout Song, currentSection: inout Song.Section) {
/// Start with a fresh line
var line = Song.Section.Line(id: currentSection.lines.count + 1)
var pattern = ""
var bottom = ""
for(index, character) in text.trimmingCharacters(in: .whitespacesAndNewlines).enumerated() {
let value = Song.Section.Line.strumCharacterDict[String(character)]
pattern += value ?? String(character)
if (index % 2) == 0 {
bottom += "=="
} else {
pattern += " "
bottom += " "
}
}
line.strum.append(pattern)
line.strum.append(bottom)
currentSection.lines.append(line)
}
// MARK: Process a line
/// Process a line
/// - Parameters:
/// - text: The text to process
/// - song: The `Song`
/// - currentSection: The current `section` of the `song`
private static func processLine(text: String, song: inout Song, currentSection: inout Song.Section) {
/// Start with a fresh line:
var line = Song.Section.Line(id: currentSection.lines.count + 1)
var partID: Int = 1
var matches = text.matches(of: lineRegex)
/// The last match is the newline character so completely empty; we don't need it
matches = matches.dropLast()
for match in matches {
let (_, chord, lyric) = match.output
var part = Song.Section.Line.Part(id: partID)
if let chord {
part.chord = processChord(chord: String(chord), song: &song).id
part.text = " "
/// Because it has a chord; it should be at least a verse
if currentSection.type == .none {
currentSection.type = .verse
currentSection.label = Environment.verse.rawValue
}
}
if let lyric {
part.text = String(lyric)
}
if !(part.empty) {
partID += 1
line.parts.append(part)
}
}
currentSection.lines.append(line)
}
// MARK: Process a chord
/// Process a chord
/// - Parameters:
/// - chord: The `chord` as String
/// - song: The `Song`
/// - Returns: The processed `chord` as String
private static func processChord(chord: String, song: inout Song) -> ChordDefinition {
/// Check if this chord is already parsed
if let match = song.chords.last(where: { $0.name == chord }) {
return match
}
/// Try to find it in the database
if var databaseChord = ChordDefinition(name: chord, instrument: song.metaData.instrument) {
if song.metaData.transpose != 0 {
databaseChord.transpose(transpose: song.metaData.transpose, scale: song.metaData.key?.root ?? .c)
/// Keep the original name
databaseChord.name = chord
}
song.chords.append(databaseChord)
return databaseChord
}
let unknownChord = ChordDefinition(unknown: chord, instrument: song.metaData.instrument)
song.chords.append(unknownChord)
return unknownChord
}
}